<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar"  :style="{ paddingTop: safeAreaInsets.top + 'px'}">
			<view class="nav-button" @click="goBack">
				<uni-icons type="left" size="20" color="#999"></uni-icons>
			</view>
			<text class="nav-title">个人信息</text>
		</view>

		<!-- 头像和昵称区域 -->
		<view class="user-info-card">
			<view class="info-item" @click="changeAvatar">
				<text class="info-label">头像</text>
				<image class="avatar" :src="fullImageUrl" mode="aspectFill" @error="handleAvatarError"></image>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
			<view class="info-item" @click="showUpdateModal('nickName')">
				<text class="info-label">昵称</text>
				<text class="info-value">{{ userInfo.nickName || '未填写' }}</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
		</view>

		<!-- 其他信息区域 -->
		<view class="user-info-card">
			<!-- 账号（不可修改） -->
			<view class="info-item disabled">
				<text class="info-label">账号</text>
				<text class="info-value">{{ userInfo.userName }}</text>
			</view>

			<view class="info-item" @click="showUpdateModal('phonenumber')">
				<text class="info-label">手机号</text>
				<text class="info-value">{{ userInfo.phonenumber || '未填写' }}</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>

			<view class="info-item" @click="showUpdateModal('email')">
				<text class="info-label">邮箱</text>
				<text class="info-value">{{ userInfo.email || '未填写' }}</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>

			<view class="info-item" @click="showSexPicker">
				<text class="info-label">性别</text>
				<text class="info-value">{{ gender }}</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>

			<view class="info-item" @click="gotoaddress">
				<text class="info-label">收货地址</text>
				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
		</view>

		<!-- 修改信息弹窗 -->
		<view v-if="showModal" class="modal-mask">
			<view class="modal-content">
				<view class="input-group">
					<text class="label">{{ currentLabel }}</text>
					<input v-if="currentField !== 'sex'" class="input" v-model="updateValue"
						:placeholder="'请输入' + currentLabel" />
				</view>
				<view class="button-group">
					<button class="button cancel" @click="cancelUpdate">取消</button>
					<button class="button confirm" @click="updateUserProfile">保存</button>
				</view>
			</view>
		</view>

		<!-- 性别选择弹窗 -->
		<view v-if="showSexModal" class="modal-mask">
			<view class="modal-content">
				<view class="radio-group">
					<view v-for="(option, index) in genderOptions" :key="index" @click="selectSex(option)"
						:class="{'selected': index === currentSexIndex}">
						<text>{{ option }}</text>
						<uni-icons type="checkmark" size="24" color="#007AFF" v-if="index === currentSexIndex" />
					</view>
				</view>
				<view class="button-group">
					<button class="button cancel" @click="cancelSexUpdate">取消</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: {
					userName: '',
					nickName: '',
					phonenumber: '',
					email: '',
					sex: '',
					avatar: ''
				},
				defaultAvatar: '/static/dis-img1.jpg', // 默认头像路径
				gender: "未知",
				showModal: false,
				currentField: '',
				currentLabel: '',
				updateValue: '',
				genderOptions: ["男", "女", "保密"],
				sexValues: ["0", "1", "2"],
				showSexModal: false,
				safeAreaInsets: {
					top: 0,
					bottom: 0
				}
			};
		},
		computed: {
			fullImageUrl() {
				return this.userInfo.avatar ?
					`http://localhost:8080${this.userInfo.avatar}` :
					this.defaultAvatar;
			},
			currentSexIndex() {
				return this.sexValues.indexOf(this.userInfo.sex?.toString());
			}
		},
		onLoad() {
			this.fetchUserProfile();
			
			this.getSafeAreaInsets();
		},
		methods: {
			//安全区域相关的方法
			getSafeAreaInsets() {
				uni.getSystemInfo({
					success: (res) => {
						this.safeAreaInsets = {
							top: res.safeArea ? res.safeArea.top : res.statusBarHeight,
							bottom: res.safeArea ? res.safeArea.bottom : 0
						};
					},
					fail: (err) => {
						console.error('获取系统信息失败:', err);
					}
				});
			},
			// 头像相关方法
			changeAvatar() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					success: (res) => {
						this.uploadAvatar(res.tempFilePaths[0]);
					}
				});
			},
			// 头像更新部分
			uploadAvatar(filePath) {
				uni.uploadFile({
					url: 'http://localhost:8080/system/user/profile/avatar',
					filePath: filePath,
					name: 'avatarfile',
					header: {
						'Authorization': uni.getStorageSync('token')
					},
					success: (res) => {
						const data = JSON.parse(res.data);
						if (data.code === 200) {
							this.userInfo.avatar = data.data;
							uni.showToast({
								title: '上传成功',
								icon: 'success'
							});
							//更新数据获取
							this.fetchUserProfile();
						}
					}
				});
			},
			handleAvatarError() {
				this.userInfo.avatar = ''; // 触发使用默认头像
			},

			// 数据获取
			async fetchUserProfile() {
				try {
					const res = await uni.request({
						url: 'http://localhost:8080/system/user/profile',
						header: {
							'Authorization': uni.getStorageSync('token')
						}
					});
					if (res.data.code === 200) {
						this.userInfo = res.data.data;
						this.gender = this.getGender(this.userInfo.sex);
					}
				} catch (error) {
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				}
			},

			// 信息修改相关
			showUpdateModal(field) {
				const allowedFields = ['nickName', 'phonenumber', 'email'];
				if (!allowedFields.includes(field)) return;

				this.currentField = field;
				this.currentLabel = this.getLabel(field);
				this.updateValue = this.userInfo[field] || '';
				this.showModal = true;
			},
			// 修改后的字段映射
			getLabel(field) {
				const labels = {
					nickName: '昵称',
					phonenumber: '手机号', // 确保与接口字段一致
					email: '邮箱'
				};
				return labels[field] || '';
			},
			// 关闭普通修改弹窗
			cancelUpdate() {
				this.showModal = false;
				this.updateValue = ''; // 清空临时数据
			},
			// 关闭性别选择弹窗
			cancelSexUpdate() {
				this.showSexModal = false;
			},
			// 性别相关
			showSexPicker() {
				this.showSexModal = true;
			},
			selectSex(option) {
				const index = this.genderOptions.indexOf(option);
				this.userInfo.sex = this.sexValues[index];
				this.gender = option;
				this.showSexModal = false;
				this.updateUserProfile();
			},
			getGender(sex) {
				return {
					'0': '男',
					'1': '女',
					'2': '保密'
				} [sex] || '保密';
			},

			// 修改后的保存方法
			updateUserProfile() {
				// 更新用户信息对象
				if (this.currentField) {
					this.userInfo[this.currentField] = this.updateValue;
				}

				uni.request({
					url: 'http://localhost:8080/system/user/profile',
					method: 'PUT',
					header: {
						'Authorization': uni.getStorageSync('token')
					},
					data: this.userInfo,
					success: () => {
						this.showModal = false;
						this.fetchUserProfile(); // 重新获取最新数据
						uni.showToast({
							title: '修改成功',
							icon: 'success'
						});
					},
					fail: (error) => {
						console.error('保存失败:', error);
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				});
			},

			goBack() {
				uni.navigateBack();
			},
			gotoaddress() {
				uni.navigateTo({
					url: '/pages/shop-address/shop-address'
				});
			}
		}
	};
</script>

<style scoped>
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	/* 顶部导航栏样式 */
	.nav-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding:  0 30rpx;
		background:white;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		position: sticky;
		top: 0;
		z-index: 10;
		height: 90rpx;
	}

	.nav-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		flex: 1;
		text-align: center;
	}

	.nav-button {
		display: flex;
		align-items: center;
	}

	/* 用户信息卡片样式 */
	.user-info-card {
		background-color: #ffffff;
		border-radius: 16rpx;
		margin: 20rpx;
		padding: 0 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.info-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	.info-item:last-child {
		border-bottom: none;
	}

	.info-label {
		font-size: 32rpx;
		color: #333;
		flex: 1;
	}

	.info-value {
		font-size: 32rpx;
		color: #666;
		text-align: right;
		margin-right: 20rpx;
		flex: 1;
	}

	.avatar {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		transition: opacity 0.3s;
	}

	/* 禁用状态样式 */
	.info-item.disabled {
		opacity: 0.7;
		pointer-events: none;
	}

	.info-item.disabled .info-value {
		color: #999;
	}

	/* 弹窗样式 */
	.modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}

	.modal-content {
		background-color: #fff;
		width: 80%;
		padding: 40rpx;
		border-radius: 16rpx;
	}

	.input-group {
		margin-bottom: 40rpx;
	}

	.label {
		display: block;
		font-size: 32rpx;
		color: #333;
		margin-bottom: 20rpx;
	}

	.input {
		height: 80rpx;
		padding: 0 20rpx;
		background-color: #f9f9f9;
		border-radius: 8rpx;
		font-size: 32rpx;
	}

	.radio-group {
		display: flex;
		padding: 20rpx;
	}

	.radio-group view {
		display: flex;
		align-items: center;
		margin-right: 20rpx;
		cursor: pointer;
	}

	.selected text {
		color: #007AFF;
	}

	.selected uni-icons {
		display: block;
	}

	.button-group {
		display: flex;
		justify-content: space-between;
		margin-top: 40rpx;
	}

	.button {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 32rpx;
		border-radius: 8rpx;
	}

	.cancel {
		background-color: #eee;
		color: #666;
		margin-right: 20rpx;
	}

	.confirm {
		background-color: #007AFF;
		color: white;
	}
</style>